/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.woundedwolf.android.tumbleweed.renderables;

import com.woundedwolf.android.tumbleweed.Pixel;
import com.woundedwolf.android.tumbleweed.elements.Renderable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;

/**
 *
 * @author FlameDuck
 */
public class Lines implements Renderable
{

	private final Object pixelLock;
	private ArrayList<Pixel> pixelList;

	public Lines()
	{
		pixelLock = new Object();
		pixelList = new ArrayList<Pixel>();
    }

	public void addLine(Pixel startPixel, Pixel endPixel)
	{
		synchronized(pixelLock)
		{
			pixelList.add(startPixel);
			pixelList.add(endPixel);
		}
	}

	public void removeLine(int index)
	{
		synchronized(pixelLock)
		{
			pixelList.remove(index);
			pixelList.remove(index);
		}
	}

	public void draw(GL10 glContext)
	{
		synchronized (pixelLock)
		{
			if (pixelList.isEmpty())
			{
					return;
			}

			// Calculate size
			int size = pixelList.size();

			float[] vertices = new float[size * 2];
			float[] colors = new float[size * 4];

			int i = 0;
			for (Pixel pixel : pixelList)
			{
				vertices[i * 2] = (int) pixel.getPosition().getXpos() + 0.5f;
				vertices[i * 2 + 1] = (int) pixel.getPosition().getYpos() + 0.5f;
				colors[i*4] = (byte) (pixel.getColor() >> 16);
				colors[i * 4 + 1] = (byte) (pixel.getColor() >> 8);
				colors[i * 4 + 2] = (byte) (pixel.getColor());
				colors[i * 4 + 3] = (byte) (pixel.getColor() >> 24);
				i++;
			}

			// Allocate vertexbuffer.
			ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
			vbb.order(ByteOrder.nativeOrder());
			FloatBuffer vertexBuffer = vbb.asFloatBuffer();
			vertexBuffer.put(vertices);
			vertexBuffer.position(0);

			ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
			cbb.order(ByteOrder.nativeOrder());
			FloatBuffer colorBuffer = cbb.asFloatBuffer();
			colorBuffer.put(colors);
			colorBuffer.position(0);

			glContext.glEnableClientState(GL10.GL_VERTEX_ARRAY);
			glContext.glEnableClientState(GL10.GL_COLOR_ARRAY);
			glContext.glVertexPointer(2, GL10.GL_FLOAT, 0, vertexBuffer);
			glContext.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);

			glContext.glDrawArrays(GL10.GL_LINES, 0, size);

			glContext.glDisableClientState(GL10.GL_COLOR_ARRAY);
			glContext.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		}
	}
}
